package com.example.lib_base.manager

import android.util.Log
import cn.bmob.v3.Bmob
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.BmobSMS
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.LogInListener
import cn.bmob.v3.listener.QueryListener
import cn.bmob.v3.listener.UpdateListener
import com.example.lib_base.model.Adv
import com.example.lib_base.model.Song
import com.example.lib_base.model.User

class BmobManager private constructor(){

    companion object {

        private var instance: BmobManager? = null

        fun getInstance(): BmobManager {
            if (instance == null) {
                synchronized(this) {
                    if (instance == null) {
                        instance = BmobManager()
                    }
                }
            }
            return instance!!
        }
    }

    /**手机号登录*/
    fun loginByPhone(phone:String,pwd:String,callback:(Boolean)->Unit){
        BmobUser.loginByAccount(phone,pwd,object :LogInListener<User>(){
            override fun done(p0: User?, p1: BmobException?) {
               callback(p1 == null)
            }
        })
    }

    /**手机号+验证码一键注册或登录*/
   fun registrationOrLogin(phone:String,code:String,callback: (Boolean) -> Unit){
       BmobUser.signOrLoginByMobilePhone(phone,code,object:LogInListener<User>(){
           override fun done(p0: User?, p1: BmobException?) {
               callback(p1==null)
           }
       })
   }

    /**用手机号修改密码*/
    fun resetPassword(pwd:String,code:String,callback: (Boolean) -> Unit){
        BmobUser.resetPasswordBySMSCode(code,pwd,object :UpdateListener(){
            override fun done(p0: BmobException?) {
                callback(p0 == null)
            }
        })
    }

    /**申请验证码*/
    fun requestSMSCode(phone:String,callback: (Boolean) -> Unit){
        BmobSMS.requestSMSCode(phone,"阿波音乐",object :QueryListener<Int>(){
            override fun done(p0: Int?, p1: BmobException?) {
                callback(p1==null)
            }
        })
    }

    /**获取当前登录用户*/
    fun getCurrentUser() = BmobUser.getCurrentUser(User::class.java)

    /**是否有用户登录*/
    fun isLogin() = BmobUser.isLogin()

    /**退出登录*/
    fun logOut(){
        BmobUser.logOut()
    }

    /**获取广告资源*/
    fun queryAdv(callback: (List<Adv>?) -> Unit){
        val advQuery = BmobQuery<Adv>()
        advQuery.findObjects(object :FindListener<Adv>(){
            override fun done(p0: MutableList<Adv>?, p1: BmobException?) {
                callback(p0)
            }
        })
    }

    /**获取歌曲资源*/
    fun querySong(callback: (List<Song>?) -> Unit){
        val songQuery = BmobQuery<Song>()
        songQuery.findObjects(object :FindListener<Song>(){
            override fun done(p0: MutableList<Song>?, p1: BmobException?) {
                callback(p0)
            }
        })
    }



}